#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include "proc.h"

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[])
{
	FILE *fp = NULL;
	int len = 0;
	unsigned char *rbuf = NULL;
	unsigned char *wbuf = NULL;
	memset(&g_data, 0, sizeof(proc_data_t));
	strcpy(g_data.ini_path_name, (char *)argv[0]);
	g_data.ini_path_name[strlen(g_data.ini_path_name)-strlen(INI_NAME)] = 0;
	path_proc(g_data.ini_path_name);
	strcpy(g_data.ini_path_name, strcat(g_data.ini_path_name, INI_NAME));
	//printf("path:%s\r\n", g_data.ini_path_name);

	if (Read_Tnifile())
		return -1;
	if ((fp = fopen(g_data.bin_path, "rb")) == NULL)
	{
		printf("[E]read bin:%s fail\r\n", g_data.bin_path);
		goto exit;
	}
	fseek(fp, 0, SEEK_END);
	len = ftell(fp);
	rewind(fp);
	rbuf = (unsigned char *)malloc(len);
	fseek(fp, 0, SEEK_SET);
	fread(rbuf, 1, len, fp);
	fclose(fp);
	
	*((volatile unsigned char*)(rbuf + g_data.bin_num_ofst)) = g_data.bin_num;
	for (int i = 0; i < g_data.bin_num; i++)
	{
		*((volatile unsigned int*)(rbuf + g_data.addr_ofst[i])) = g_data.addr[i];
		*((volatile unsigned int*)(rbuf + g_data.len_ofst[i])) = g_data.len[i];
		printf("#%d addr_ofst:%#x,addr:%#x,len_ofst:%#x,len:%#x\r\n", i, g_data.addr_ofst[i], g_data.addr[i], g_data.len_ofst[i], g_data.len[i]);
	}

	fp = fopen(g_data.bin_path, "wb");
	fwrite(rbuf, 1, len, fp);
	fclose(fp);

	free(rbuf);
	exit:
	Write_Tnifile();
	return 0;
}
